#include <xp/bas/stdcli.h>
#include <xp/bas/stdio.h>

/*
ls /permission=abcdef
ls /permission abcdef
ls --permission abcdef
dir /permission=(owner:rwed,group:rwed) /owned_by=bacon
*/

int handle_cli_error (
	const xp_cli_t* cli, int code, 
	const xp_char_t* name, const xp_char_t* value)
{
	xp_printf (XP_TEXT("usage: %s [/owner=owner] [/permission] [/protection=protection]\n"), cli->verb);

	if (code == XP_CLI_ERROR_INVALID_OPTNAME) {
		xp_printf (XP_TEXT("unknown option - %s\n"), name);
	}
	else if (code == XP_CLI_ERROR_REDUNDANT_OPTVAL) {
		xp_printf (XP_TEXT("redundant value %s for %s\n"), value, name);
	}
	else if (code == XP_CLI_ERROR_MISSING_OPTVAL) {
		xp_printf (XP_TEXT("missing value for %s\n"), name);
	}
	else if (code == XP_CLI_ERROR_MEMORY) {
		xp_printf (XP_TEXT("memory error in processing %s\n"), name);
	}
	else {
		xp_printf (XP_TEXT("error code: %d\n"), code);
	}

	return -1;
}

int xp_main (int argc, xp_char_t* argv[])
{
	int i;

	static const xp_char_t* optsta[] = 
	{
		XP_TEXT("/"), XP_TEXT("--"), XP_NULL
	};

	static xp_cliopt_t opts[] =
	{
		{ XP_TEXT("owner"), XP_CLI_OPTNAME | XP_CLI_OPTVAL },
		{ XP_TEXT("permission"), 0 },
		{ XP_TEXT("protection"), XP_CLI_OPTNAME | XP_CLI_OPTVAL },
		{ XP_NULL, 0 }
	};

	xp_cli_t cli =
	{
		handle_cli_error,
		optsta,
		XP_TEXT("=:"),
		opts
	};

	xp_cliopt_t* qp = opts;

	if (xp_parsecli (argc, argv, &cli) == -1) return -1;

	xp_printf (XP_TEXT("-- present options -- \n"));
	while (qp->name != XP_NULL) {
		xp_printf (XP_TEXT("%s: %s\n"), qp->name,
			(xp_getclioptval (&cli, qp->name) != XP_NULL? 
				XP_TEXT("present"): XP_TEXT("not present")));
		qp++;
	}

	xp_printf (XP_TEXT("-- option values --\n"));
	qp = cli.opts;
	while (qp->name != XP_NULL) {
		if (qp->value != XP_NULL) {
			xp_printf (XP_TEXT("%s: %s\n"), qp->name, qp->value);
		}
		qp++;
	}

	xp_printf (XP_TEXT("-- parameters --\n"));
	for (i = 0; i < xp_getncliparams(&cli); i++) {
		xp_printf (XP_TEXT("%d. %s\n"), i, cli.params[i]);	
	}

	xp_clearcli (&cli);
	return 0;
}
